package com.example.net.update

import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import com.example.baseutils.*
import com.example.baseutils.net.NetListtenr
import com.example.baseutils.net.NetState
import java.util.concurrent.Executors
import kotlin.concurrent.thread

/**
 * 数据拉取服务
 * */
class PullDataService : Service(), NetListtenr {
    private val thredPool = Executors.newSingleThreadExecutor()
    private var running = false

    companion object {
        private const val TAG = "PullDataService"
        const val KEY_1 = "KEY_1"
        const val KEY_1_VALUE = "KEY_1_VALUE"

        fun refreshData(context: Context) {
            "刷新数据DataService".log(TAG)
            val intent = Intent(context, PullDataService::class.java)
            intent.putExtra(KEY_1, KEY_1_VALUE)
            context.startService(intent)
        }
    }


    private val handler: Handler = Handler(Looper.getMainLooper())
    override fun onBind(intent: Intent): IBinder {
        TODO("Return the communication channel to the service.")
    }

    override fun onCreate() {
        super.onCreate()
        "拉取数据服务启动".log(TAG)

        NetState.getInstance().addListtner(this)
        running = true

//        thredPool.execute {
//            while (running) {
//                "请求是否更新二维码和人员信息".log(TAG)
//                try {
//                    RetrofitCreator.callUpdateState()
//                } catch (e: Exception) {
//                    e.printStackTrace()
//                    "${e.message}".log(TAG, LogUtils.LogLevel.E)
//                    TimeUtil.delayMs(10 * 1000)
//                }
//            }
//        }

    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        "onStartCommand".log(TAG)
        intent?.getStringExtra(KEY_1)?.let {
            when (it) {
                KEY_1_VALUE -> {
                    "收到 KEY_1_VALUE 准备更新职工数据".log(TAG)
                    refresh()
                }
                else -> {
                    "收到其他信息 $it".log(TAG)
                }
            }
        }


        return super.onStartCommand(intent, flags, startId)
    }

    private fun refresh() {
        "refresh 刷新数据".log(TAG)
        handler.removeCallbacksAndMessages(null)
        handler.postDelayed({
            thread {
                "准备重新更新职工数据".log(TAG)
                getStudent()
            }
        }, 5000)
    }

    @Synchronized
    private fun getStudent() {
        //获取学校信息

    }

    override fun onDestroy() {
        super.onDestroy()
        "销毁服务".log(TAG)
        NetState.getInstance().removeListtner(this)
        running = false
        thredPool.shutdownNow()
    }

    override fun netState(state: Boolean) {
        if (!state) {
            "网络异常不加载数据".log(TAG)
            return
        }
        refresh()
    }


}
